package cn.com.zetatech.loader.util;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.StringTokenizer;

public class FTPUploadUtil {

    /**
     * 上传BufferedImage到SFTP服务器
     *
     * @param bufferedImage BufferedImage对象
     * @param sftpHost      SFTP服务器IP
     * @param sftpPort      SFTP服务器端口
     * @param sftpUser      SFTP用户名
     * @param sftpPassword  SFTP密码
     * @param remotePath    SFTP服务器上存储图像的路径（包含文件名）
     * @throws IOException 如果发生IO错误
     */
    public static void uploadImageToSFTP(BufferedImage bufferedImage, String sftpHost, int sftpPort, String sftpUser, String sftpPassword, String remotePath) throws Exception {
        Session session = null;
        ChannelSftp channelSftp = null;

        try {
            // 初始化JSch对象
            JSch jsch = new JSch();
            session = jsch.getSession(sftpUser, sftpHost, sftpPort);
            session.setPassword(sftpPassword);

            // 配置SFTP会话属性
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);

            // 连接并打开会话
            session.connect();

            // 打开SFTP通道
            channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();

            // 提取远程目录和文件名
            String remoteDir = remotePath.substring(0, remotePath.lastIndexOf('/'));
            String remoteFileName = remotePath.substring(remotePath.lastIndexOf('/') + 1);

            // 创建远程目录（如果不存在）
            createRemoteDirectories(channelSftp, remoteDir);

            // 将BufferedImage转换为输入流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", baos);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(baos.toByteArray());

            // 存储文件
            channelSftp.put(inputStream, remotePath);
            inputStream.close();

        } finally {
            // 断开连接
            if (channelSftp != null && channelSftp.isConnected()) {
                channelSftp.disconnect();
            }
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }

    private static void createRemoteDirectories(ChannelSftp channelSftp, String remoteDir) throws Exception {
        StringTokenizer tokenizer = new StringTokenizer(remoteDir, "/");
        String path = "";
        while (tokenizer.hasMoreTokens()) {
            String dir = tokenizer.nextToken();
            path += "/" + dir;
            try {
                channelSftp.cd(path);
            } catch (Exception e) {
                channelSftp.mkdir(path);
                channelSftp.cd(path);
            }
        }
        channelSftp.cd("/");
    }
}
